'use strict';

import DeviceInfo from 'react-native-device-info';
import { DeviceEventEmitter, AsyncStorage } from 'react-native';
import { HOST } from '../constants/Config';
import { ERROR_HANDLE_TOAST } from '../constants/Global';

const timeOut = 1000 * 120;
const LogindefaultOptions = {
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json;charset=UTF-8',
    cnVer: 'V1',
    cnUser: 1568,
  },
};
const toastHandler = msg => {
  DeviceEventEmitter.emit(ERROR_HANDLE_TOAST, msg);
};

const checkStatus = (res, url, options) => {
  console.log(res);
  const { code } = res; //这里可以这样写 如果token失效  然后借口返回特殊状态码， 然后跳转到登录。
  if (code == 4011) {
    AsyncStorage.multiRemove(['token', 'userId']);
    toastHandler('登录失效，请重新登录');
    //跳转登录
    global.nav.push('Auth');
  } else {
    return res;
  }
};

const request = (url, options) => {
  console.log('options:' + JSON.stringify(options));
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      toastHandler('连接超时');
      reject(new Error('连接超时...'));
    }, timeOut);

    fetch(url, options)
      .then(res => {
        console.log(res);
        clearTimeout(timeoutId);
        return res.json();
      })
      .then(res => checkStatus(res, url, options))
      .then(res => resolve(res))
      .catch(err => {
        toastHandler(err);
        throw new Error('catch' + err);
      });
  });
};

/**
 * 请求url，返回promise 对象
 *
 * @param  {string} api       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 */

// GET(HOME_HISTORY).then(res => dispatch(setReduxData(res.Data[0].telephone)))
// GET(PRODUCT_DETAIL, { id: 1 }).then(res => console.log(res))

// POST(CAPTCHA_VERIFY, {
//   code: 1,
//   random: 0
// }).then(res => console.log(res))

export const GET = (api, params) => {
  let url;

  if (params) {
    const stringifyParams = Object.keys(params)
      .reduce((acc, cur) => acc.concat([`${cur}=${params[cur]}`]), [])
      .join('&');
    url = `${HOST + api}?${stringifyParams}`;
  } else {
    url = HOST + api;
  }
  let tokenObj = {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=UTF-8',
      cnVer: 'V1',
      cnUser: 1568,
      token: global.token,
      userId: global.userId,
    },
  };
  return request(url, tokenObj);
};

export const POST = (api, params = {}) => {
  const url = HOST + api;
  const options = {
    method: 'POST',
    body: JSON.stringify(params),
  };
  let tokenObj = {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=UTF-8',
      cnVer: 'V1',
      cnUser: 1568,
      token: global.token,
      userId: global.userId,
    },
  };
  return request(url, { ...tokenObj, ...options });
};

export const LOGIN_POST = (api, params) => {
  const url = HOST + api;
  const options = {
    method: 'POST',
    body: JSON.stringify(params),
  };

  return request(url, { ...LogindefaultOptions, ...options });
};

export const GET_GPRS = params => {
  const url = `http://gc.ditu.aliyun.com/regeocoding`;
  const stringifyParams = Object.keys(params)
    .reduce((acc, cur) => acc.concat([`${cur}=${params[cur]}`]), [])
    .join('&');
  let newUrl = `${url}?${stringifyParams}`;
  const options = {
    method: 'GET',
  };

  return request(newUrl, {
    headers: {
      'Content-Type': 'charset=UTF-8',
    },
  });
};
